package boss.portal.service.impl;

import boss.portal.param.PowerOnRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

@Service
@Log4j2
public class WebClientService {

    private final WebClient webClient;

    @Value("${charge_url}")
    private String chargeUrl;

    public WebClientService(WebClient.Builder builder) {
        this.webClient = builder.baseUrl(chargeUrl).build();
    }

    public String getJson(String path) {
        return this.webClient.get().uri(path).retrieve().bodyToMono(String.class).block();
    }

    public   Flux<String> doPowerOn(PowerOnRequest req, String headerValue) {
        System.out.println("Exiting NON-BLOCKING Controller!");
        log.info("jsonStr========="+ JSONUtil.toJsonStr(req));
        log.info("header========"+headerValue);

        Flux<String> tweetFlux = WebClient.create()
                .post()
                .uri(chargeUrl+"/microcharge/poweron")
                .header("deviceNo", headerValue)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(req))
                .retrieve()
                .bodyToFlux(String.class);

        log.info("doPowerOn!");
        tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
        log.info("=================finish!");
        return tweetFlux;
    }

}

